import TodoEvent from "./js/TodoEvent";
import { ITodoData } from "./js/typing";

((doc) => {

    const OInput: HTMLInputElement = doc.querySelector('input');
    const OAddBtn: HTMLElement = doc.querySelector('button');
    const OTodoList: HTMLElement = doc.querySelector('.todo-list');

    const todoData: ITodoData[] = []

    const todoEvent: TodoEvent = new TodoEvent(todoData, OTodoList);

    const init = (): void => {
        bindEvent();
    }

    function bindEvent(): void {
        OAddBtn.addEventListener('click', handleAddBtnClick, false);
        OTodoList.addEventListener('click', handleListClick, false);
    }

    function handleAddBtnClick(): void {
        const val: string = OInput.value.trim();

        if(val.length) {
            const ret = todoEvent.addTodo(<ITodoData>{
                id: new Date().getTime(),
                content: val,
                completed: false
            });

            if (ret && ret === 1001) {
                alert('列表已存在');
                return;
            }

            OInput.value = '';
        }  
    }

    function handleListClick(e: MouseEvent): void {
        const tar = e.target as HTMLElement;
        const tagName = tar.tagName.toLowerCase();

        if (tagName === 'input' || tagName === 'button') {
            const id = parseInt(tar.dataset.id);
            switch (tagName) {
                case 'input':
                    todoEvent.toggleCompleted(tar, id);
                    break;
                case 'button':
                    todoEvent.removeTodo(tar, id);
                    break;
                default:
                    break;
            }
        }
    }


    init();
})(document);